<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="6">
            <a-form-model-item
              label="单据编号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="commonInstockBillNo"
            >
              <a-input v-model="model.commonInstockBillNo" placeholder="请输入单据编号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="入库类型"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="instockType"
            >
              <j-dict-select-tag
                type="list"
                v-model="model.instockType"
                ref="dictSelect"
                placeholder="请选择入库类型"
                :disabled="isFromPurchase"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="仓库名称"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="instockWareno"
            >
              <!-- <j-dict-select-tag
                type="list"
                v-model="model.instockWareno"
                dictCode="erp_warehouse,name,code,type in
(select t1.erp_warehouse_no from erp_category_warehouse_type t1
left join erp_goods_classification t2 on t1.erp_category_no=t2.category_no
left join erp_warehouse_type t3 on t1.erp_warehouse_no=t3.warehouse_type_no
where t2.category_manage_type=1 and t3.del_flag='0' )"
                placeholder="请选择仓库编号"
              />-->
              <a-select v-model="model.instockWareno" @change="handleWareHouseChange">
                <a-select-option v-for="(item, key) in wareOptions" :key="key" :value="item.code">
                  <span
                    style="display: inline-block;width: 100%"
                    :title=" item.name || item.label "
                  >{{ item.name || item.label }}</span>
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="审批流程"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="flowType"
            >
              <a-input v-model="model.flowType" placeholder="请输入审批流程" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="上级单号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="parentBillNo"
            >
              <a-input
                v-model="model.parentBillNo"
                placeholder="请输入上级单号"
                :disabled="isFromPurchase"
              ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="入库日期"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="instockDate"
            >
              <j-date placeholder="请选择入库日期" v-model="model.instockDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="供应商"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="supplierNo"
            >
              <a-input
                v-model="model.supplierName"
                placeholder="请输入供应商编号"
                :disabled="isFromPurchase"
              ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="经办人"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="relativeBy"
            >
              <a-input-search
                v-model="model.relativeName"
                placeholder="请输入经办人"
                readonly
                enter-button
                @search="handleSelectUser"
                :disabled="formDisabled"
              ></a-input-search>
              <a-input v-model="model.relativeBy" hidden></a-input>
            </a-form-model-item>
          </a-col>
          <Tsl-Select-User-Single ref="selectUserModal" @selectFinished="selectOK"></Tsl-Select-User-Single>
          <a-col :span="6">
            <a-form-model-item
              label="批次号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="batchNo"
            >
              <a-input v-model="model.batchNo" placeholder="请输入批次" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="生产车间"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="workShopNo"
            >
              <a-input v-model="model.workShopNo" placeholder="请输入车间编号" :disabled="isFromPurchase"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="制单日期"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="createTime"
            >
              <a-input v-model="model.createTime" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="6">
            <a-form-model-item
              label="客户编号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="customerNo"
            >
              <a-input v-model="model.customerNo" placeholder="请输入客户编号"></a-input>
            </a-form-model-item>
          </a-col>-->
          <a-col :span="6">
            <a-form-model-item
              label="备注"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="remark"
            >
              <a-input v-model="model.remark" placeholder="请输入备注"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="入库信息" :key="refKeys[0]" :forceRender="true">
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="tslCommonInstockBillDetialTable.loading"
          :columns="tslCommonInstockBillDetialTable.columns"
          :dataSource="tslCommonInstockBillDetialTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="false"
          :rowSelection="true"
          :toolbar="true"
          :toolbarConfig="{ slot: ['prefix', 'suffix'], btn: [] }"
          @edit-closed="editClosedEvent"
        >
          <template v-slot:toolbarSuffix>
            <a-button
              type="primary"
              icon="PlusCircleOutlined"
              @click="addMateriel"
              :disabled="formDisabled"
            >新增</a-button>
          </template>
          <template #wareLocatorNo="{ row }">
            <a-select :disabled="formDisabled" v-model="row.wareLocatorNo" style="width: 100%">
              <a-select-option
                v-for="item in locatorOptions"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              >{{ item.name }}</a-select-option>
            </a-select>
          </template>
          <template v-slot:action="props">
            <a-popconfirm v-show="!formDisabled" title="确定删除吗？" @confirm="handleDelDetail(props)">
              <a>删除</a>
            </a-popconfirm>
          </template>
        </j-vxe-table>
      </a-tab-pane>
      <a-tab-pane tab="库存信息" :key="refKeys[1]">
        <j-vxe-table
          keep-source
          :ref="refKeys[1]"
          :loading="tslCommonCurStockBillDetialTable.loading"
          :columns="tslCommonCurStockBillDetialTable.columns"
          :dataSource="tslCommonCurStockBillDetialTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="false"
        />
      </a-tab-pane>
    </a-tabs>

    <erp-goods-list-modal
      ref="selectMaterial"
      @handlerOk="onMaterialSelected"
      checkval="checkbox"
      :category="3"
    ></erp-goods-list-modal>
  </a-spin>
</template>

<script>
import { getAction, httpAction, postAction, putAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import store from '@/store'
import moment from 'dayjs'
import TslSelectUserSingle from '@/components/tsl/TslSelectUserSingle.vue'
import ErpGoodsListModal from '@/views/modules/goods/ErpGoodsListModal'

export default {
  name: 'TslCommonInstockBillForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer,
    TslSelectUserSingle,
    ErpGoodsListModal,
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: {
        commonInstockBillNo: '',
        instockDate: '',
        flowType: '无',
        tslCommonInstockBillDetialList: [],
        instockWareno: '03',
        supplierNo: '',
        supplierName: '',
        instockType: '',
        relativeBy: '',
      },
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        commonInstockBillNo: [{ required: true, message: '请输入单据编号!' }],
        instockType: [{ required: true, message: '请选择入库类型!' }],
        instockWareno: [{ required: true, message: '请选择仓库!' }],
        relativeBy: [{ required: true, message: '请选择经办人!' }],
        instockDate: [{ required: true, message: '请选择入库日期!' }],
      },
      refKeys: ['tslCommonInstockBillDetial', 'tslCommonCurStockBillDetial'],
      tableKeys: ['tslCommonInstockBillDetial'],
      activeKey: 'tslCommonInstockBillDetial',
      // 五金配件入库单明细
      tslCommonInstockBillDetialTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '序号',
            key: 'seq',
            type: JVXETypes.normal,
            width: '60px',
            placeholder: '请输入${title}',
          },
          {
            title: '物料编号',
            key: 'materialNo',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            validateRules: [
              {
                required: true, // 必填
                message: '请输入${title}', // 显示的文本
              },
            ],
          },
          {
            title: '物料名称',
            key: 'materialName',
            type: JVXETypes.normal,
            width: '180px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '规格',
            key: 'spec',
            type: JVXETypes.normal,
            width: '150px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '主计量',
            key: 'meUnit',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '数量',
            key: 'meNum',
            type: JVXETypes.input,
            width: '100px',
            placeholder: '请输入${title}',
            validateRules: [
              {
                required: true, // 必填
                message: '请输入${title}', // 显示的文本
              },
            ],
          },
          {
            title: '辅助单位',
            key: 'auUnit',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '辅助数量',
            key: 'auNum',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '备注',
            key: 'remark',
            type: JVXETypes.input,
            width: '120px',
            defaultValue: '',
          },
          {
            title: '库位',
            key: 'wareLocatorNo',
            type: JVXETypes.slot,
            width: '150px',
            placeholder: '请输入${title}',
            slotName: 'wareLocatorNo',
            validateRules: [
              {
                required: true, // 必填
                message: '请输入${title}', // 显示的文本
              },
            ],
          },
          {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            minWidth: '100px',
            align: 'center',
            slotName: 'action',
          },
        ],
      },
      tslCommonCurStockBillDetialTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '物料编号',
            key: 'materialNo',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '物料名称',
            key: 'materialName',
            type: JVXETypes.normal,
            width: '180px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '规格',
            key: 'spec',
            type: JVXETypes.normal,
            width: '150px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '主计量',
            key: 'meUnit',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '数量',
            key: 'meNum',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '辅助单位',
            key: 'auUnit',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '辅助数量',
            key: 'auNum',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '库位',
            key: 'wareLocatorNo',
            type: JVXETypes.normal,
            width: '150px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
        ],
      },
      url: {
        add: '/storage/tslCommonInstockBill/add',
        edit: '/storage/tslCommonInstockBill/edit',
        queryById: '/storage/tslCommonInstockBill/queryById',
        tslCommonInstockBillDetial: {
          list: '/storage/tslCommonInstockBill/queryTslCommonInstockBillDetialByMainId',
        },
        locatorUrl: '/base/erpLocation/list',
      },
      wareOptions: [],
      locatorOptions: [],
      isFromPurchase: true,
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    customFormData: {
      type: Object,
      default: () => {
        return {}
      },
      required: false,
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
    this.model.instockDate = moment().format('YYYY-MM-DD')
    this.model.batchNo = moment().format('YYYYMMDD')
    let user = store.getters.userInfo
    if (!this.model.createBy) {
      this.model.createBy = user.username
      this.model.sysOrgCode = user.departIds
    }

    //如果是审批流进来的时候要将审批流的数据显示出来
    if (this.customFormData.id != null) {
      this.model = this.customFormData
      //刷新子表数据
      this.editAfter()
    }

    this.getWareHouseOptions()

    //加载默认仓库库位
    this.getLocatorOptions(this.model.instockWareno)
  },
  mounted() {
    //dictSelect
    this.$refs.dictSelect.setCurrentDictOptions([
      // { label: '五金配件请购入库', value: '10127' },
      // { label: '通用领料赤字入库', value: '10147' },
      { label: '手填入库', value: '10110' },
      { label: '盘盈入库', value: '10116' },
    ])
  },
  methods: {
    generateBillNo() {
      let url = '/sys/fillRule/executeRuleByCode/tsl_common_instock_bill'
      putAction(url, {}).then((res) => {
        // 执行成功，获取返回的值，并赋到页面上
        if (res.success) {
          this.model.commonInstockBillNo = res.result
        }
      })
    },
    addBefore() {
      this.tslCommonInstockBillDetialTable.dataSource = []
      this.tslCommonCurStockBillDetialTable.dataSource = []
    },
    add() {
      this.generateBillNo()

      this.tslCommonInstockBillDetialTable.dataSource = []
      this.tslCommonCurStockBillDetialTable.dataSource = []

      this.isFromPurchase = store.getters.isFromPurchase
      let tempList = store.getters.selectSparePurchaseBillDetail
      console.log(tempList)
      if (tempList.length > 0) {
        tempList.forEach((row, index) => {
          this.tslCommonInstockBillDetialTable.dataSource.push({
            materialId: row.materialId,
            materialNo: row.materialNo,
            materialName: row.materialName,
            materialDesc: row.materialDesc,
            spec: row.spec,
            meNum: row.num,
            meUnit: row.unit,
            auUnit: row.auUnit_dictText,
            auNum: row.auNum,
            remark: row.remark,
            sourceBillDetailId: row.detailId,
            coRate: row.coRate,
            seq: index + 1,
          })
        })
        this.model.instockType = '10127'
        this.model.parentBillNo = tempList[0].billNo
        this.model.supplierNo = tempList[0].supplierNo
        this.model.supplierName = tempList[0].supplierName
      }
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {})
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.tslCommonInstockBillDetial.list, params, this.tslCommonInstockBillDetialTable)
      }
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            if (allValues.tablesValue[0].tableData.length <= 0) {
              this.$message.warning('订单明细不能为空')
              return
            }
            resolve(allValues)
          })
          .catch((e) => {
            if (e.error === VALIDATE_FAILED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        tslCommonInstockBillDetialList: allValues.tablesValue[0].tableData,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    getWareHouseOptions() {
      let that = this
      getAction('/base/erpWarehouse/listForType', { manageTypeNo: '1' }).then((res) => {
        if (res.result && res.result.length > 0) {
          that.wareOptions = res.result
          // if (that.wareOptions && that.wareOptions.length > 0) {
          //   that.model.instockWareno = that.wareOptions[0].code
          // }
        }
      })
    },
    getLocatorOptions(wareNo) {
      if (wareNo) {
        getAction(this.url.locatorUrl, { warehouseCode: wareNo, pageNo: 1, pageSize: 3000 }).then((res) => {
          if (res.result.records && res.result.records.length > 0) {
            this.locatorOptions = res.result.records
          }
        })
      }
    },
    handleWareHouseChange(value) {
      this.getLocatorOptions(value)

      if (
        this.tslCommonInstockBillDetialTable.dataSource &&
        this.tslCommonInstockBillDetialTable.dataSource.length > 0
      ) {
        let arr = this.tslCommonInstockBillDetialTable.dataSource
        arr.forEach((element) => {
          if (element.wareLocatorNo) {
            element.wareLocatorNo = ''
          }
        })
      }
    },
    handleSelectUser() {
      this.$refs.selectUserModal.visible = true
    },
    selectOK(data) {
      this.model.relativeName = data.employeeName
      this.model.relativeBy = data.employeeCode
      this.$forceUpdate()
    },
    handleDelDetail(props) {
      props.target.removeRows(props.row)
      if (this.tslCommonInstockBillDetialTable.dataSource.length > 0) {
        this.tslCommonInstockBillDetialTable.dataSource.splice(
          this.tslCommonInstockBillDetialTable.dataSource.findIndex((d) => d.id === props.row.id),
          1
        )

        this.tslCommonInstockBillDetialTable.dataSource.forEach((element, index) => {
          element.seq = index + 1
        })
      }
    },
    addMateriel() {
      this.$nextTick(() => {
        this.$refs.selectMaterial.add()
      })
      // if (this.model.instockType === '10110' || this.model.instockType === '10116') {
      //   this.$nextTick(() => {
      //     this.$refs.selectMaterial.add()
      //   })
      // } else {
      //   this.$message.warning('当前入库类型不能单独选择物料')
      //   return
      // }
    },
    onMaterialSelected(rows) {
      let curSeq = 0
      if (
        this.tslCommonInstockBillDetialTable.dataSource &&
        this.tslCommonInstockBillDetialTable.dataSource.length > 0
      ) {
        curSeq = this.tslCommonInstockBillDetialTable.dataSource.length
      }
      rows.forEach((row, index) => {
        let detail = {
          materialId: row.id,
          materialNo: row.code,
          materialName: row.name,
          spec: row.noneSpec,
          meNum: row.num,
          meUnit: row.meUnit_dictText,
          auNum: 0,
          auUnit: row.auUnit_dictText,
          remark: row.remark,
          coRate: row.coRate,
          seq: curSeq + index + 1,
        }
        this.tslCommonInstockBillDetialTable.dataSource.push(detail)
      })
    },
    editClosedEvent({ row, column, cellValue }) {
      if (column.property === 'meNum') {
        if (row.meNum && row.coRate) {
          row.auNum = (row.meNum * row.coRate).toFixed(2)
        }
      }
    },
  },
}
</script>

<style scoped>
</style>